<script setup lang="ts">
import { ref, onMounted } from 'vue'

import { useRoute } from 'vue-router'
import { get, post, isWechat } from '@/utils/service'
import { VUE_APP_BASE_API } from '@/utils/baseConfig'
import { initWehcatShare, shareType } from '@/utils/share'
import { showFailToast, showNotify } from 'vant' //
import sharePerson from '@/components/sharePerson.vue'
const router = useRoute()
const showSignDialog = ref(false)
const actCode = router.query.actCode
const shareRecordNo = router.query.shareRecordNo || ''
const shareMemberId = router.query.shareMemberId || -1
const shareMemberState = ref(false)
const actActivity = ref({})
const actImages = ref([])
const shareMemberInfo = ref({})
const LIKE_NORMAL_IMAGE = VUE_APP_BASE_API + '/images/vue/like.png'
const LIKE_LIKED_IMAGE = VUE_APP_BASE_API + '/images/vue/liked.png'
const likeImage = ref(LIKE_NORMAL_IMAGE)
const custName = ref('')
const mobilePhone = ref('')
const jionPersonNum = ref(1)
const loadingStatus = ref(false)
const richTextContent = ref()
const isWechatState = ref(false)
const shareData = ref({})
const url = window.location.href.split('#')[0]
onMounted(() => {
  isWechatState.value = isWechat()
  try {
    get('/actActivityWechatNew/readAgentRewardWechat', {
      actCode: actCode,
      shareCode: shareRecordNo,
    }).then((res) => {
      const data = res.data
      shareData.value.title = data.name
      shareData.value.desc = data.intro
      shareData.value.link = url
      shareData.value.imgUrl = VUE_APP_BASE_API + data.frontPicture
      const actImagesList = data.actImages
      actActivity.value = data.actActivity
      if (actActivity.value.likeState == 1) {
        likeImage.value = LIKE_NORMAL_IMAGE
      } else {
        likeImage.value = LIKE_LIKED_IMAGE
      }
      richTextContent.value = addDomainToSrcWithDOM(actActivity.value.role, VUE_APP_BASE_API)
      actImages.value = actImagesList.map((img) => ({
        ...img,
        picture: VUE_APP_BASE_API + img.url,
        dbid: img.dbid,
      }))
      initWehcatShare(shareData.value, url, isWechatState.value, shareType.SHARE_WECHAT_ACTITY) //生成分享数据
    })
    getShareMember()
  } catch (error) {
    console.log('onMounted error:' + error)
  }
})

function getShareMember() {
  get('/memberWechatNew/queryWechatShareMemberById', {
    shareMemberId: shareMemberId,
  }).then((res) => {
    if (res.code == 0) {
      shareMemberState.value = true
      const data = res.data
      shareMemberInfo.value = data
      if (data.user == null) {
        shareMemberState.value = false
      }
    } else {
      shareMemberState.value = false
    }
  })
}
function likeNews() {
  const likeState = actActivity.value.likeState
  get('/actActivityWechatNew/saveParseActivityRecordWechat', {
    actCode: actCode,
    shareCode: shareRecordNo,
    type: likeState,
  }).then((res) => {
    const data = res.data
    if (data != null) {
      actActivity.value.likeState = data.likeState
      if (data.likeState == 1) {
        likeImage.value = LIKE_NORMAL_IMAGE
      } else {
        likeImage.value = LIKE_LIKED_IMAGE
      }
      actActivity.value.praiseNum = data.praiseNum || 0
    }
  })
}
function addDomainToSrcWithDOM(html: string, domain: string) {
  //富文本图片添加域名
  const parser = new DOMParser()
  const doc = parser.parseFromString(html, 'text/html')
  const images = doc.querySelectorAll('img')

  images.forEach((img) => {
    const src = img.getAttribute('src') || null
    if (null != src && !src.startsWith('http')) {
      img.setAttribute('src', `${domain}${src}`)
    }
  })

  return new XMLSerializer().serializeToString(doc.body)
}
function onClickLeft() {
  window.history.back()
}
function onFailed(errorInfo: Error | string) {
  console.log('failed', errorInfo)
}
function submitFrm(values: object) {
  //保存报名
  loadingStatus.value = true // 显示加载状态
  try {
    values.name = custName.value || ''
    values.actActivityId = actActivity.value.dbid || ''
    post('/actActivityWechatNew/saveActCustomer', values).then((res) => {
      if (res.code === 0) {
        showNotify({ type: 'success', message: res.msg, duration: 3000 })
        setTimeout(() => {
          actActivity.value = res.data
          showSignDialog.value = false
        }, 1000)
      } else {
        showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
      }
    })
  } catch (error) {
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function phoneValidator() {
  return /^1\d{10}$/.test(mobilePhone.value)
}
function nameValidator() {
  return /^[\u4e00-\u9fa5]{2,10}$/.test(custName.value)
}
function jionPersonNumValidator() {
  if (jionPersonNum.value >= 1 || jionPersonNum.value <= 5) {
    return true
  }
  return false
}
function onReport() {
  const isWechatSt = isWechatState.value
  if (isWechatSt) {
    showSignDialog.value = true
  } else {
    showFailToast('操作失败，请在微信微信端报名')
  }
}
</script>
<template>
  <van-nav-bar title="活动明细" left-text="返回" left-arrow @click-left="onClickLeft" />
  <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white" height="200">
    <van-swipe-item v-for="item1 in actImages" v-bind:key="item1.dbid">
      <img :src="item1.picture" alt="" width="100%" height="100%" />
    </van-swipe-item>
  </van-swipe>
  <div class="cardActivityContentDetailTitle">
    <h2>{{ actActivity.title }}</h2>
    <p style="color: var(--main-color)">{{ actActivity.jionNum }}已经报名</p>
  </div>
  <div class="cardActivityContentParam">
    <div class="contentTime">
      <label>报名时间：</label>
      <span>{{ actActivity.signUpBeginTime }}至{{ actActivity.signUpEndTime }}</span>
    </div>
    <div class="contentTime">
      <label>活动时间:</label>
      <span class="price">{{ actActivity.actActtivityDateStr }}</span>
    </div>
    <div class="contentTime">
      <label>活动地点:</label>
      <span class="price">{{ actActivity.actAddress }}</span>
    </div>
  </div>
  <sharePerson :item="shareMemberInfo" v-if="shareMemberState" />
  <van-tabs
    v-model:active="active"
    type="card"
    style="width: 100%"
    title-active-color="#FFF"
    color="#c82030"
    title-inactive-color="#c82030"
  >
    <van-tab title="活动详情">
      <div class="newsRichContent" v-html="richTextContent"></div>
    </van-tab>
    <van-tab title="活动规则">
      <pre class="cardActivityContentPre">{{ actActivity.intro }}</pre>
    </van-tab>
  </van-tabs>

  <div class="buyChery">买奇瑞一定来瑞一看看！！！</div>
  <van-row class="" style="line-height: 30px">
    <van-col span="6"
      >阅读量：<span class="newNum">{{ actActivity.readNum }}</span></van-col
    >
    <van-col span="6"
      >点赞量：<span class="newNum">{{ actActivity.praiseNum }}</span></van-col
    >
    <van-col span="6"
      >分享量：<span class="newNum">{{ actActivity.shareNum }}</span></van-col
    >
    <van-col
      span="6"
      style="text-align: right; cursor: pointer"
      v-if="isWechatState"
      :onclick="likeNews"
    >
      <img :src="likeImage" alt="" width="30" height="30" />
    </van-col>
  </van-row>
  <div class="newsFooter">
    <div class="copyright">Copyright@2025 成都易成致达网络科技提供技术支持</div>
  </div>
  <br />
  <van-action-bar>
    <van-action-bar-icon icon="home-o" to="/" text="主页" color="#c82030" />
    <van-action-bar-button
      v-if="actActivity.activityState == 5"
      color="#c82030"
      type="danger"
      text="报名"
      v-on:click="onReport"
    /><!--报名可用按钮-->
    <van-action-bar-button
      v-else
      color="#c82030"
      type="danger"
      disabled
      :text="actActivity.activityStateName"
    /><!--其他情形按钮-->
  </van-action-bar>
  <van-popup
    closeable
    v-model:show="showSignDialog"
    position="bottom"
    round
    :style="{ padding: '60px 20px' }"
  >
    <div style="padding-bottom: 30px">
      <h1 style="text-align: center">活动报名</h1>
    </div>
    <van-form @failed="onFailed" @submit="submitFrm">
      <van-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          v-model="custName"
          required="true"
          label="姓名"
          name="custName"
          placeholder="客户姓名"
          :rules="[
            { required: true, message: '请填写姓名' },
            { validator: nameValidator, message: '请输入报名人姓名,2-10个中文字符' },
          ]"
        />
        <van-field
          v-model="mobilePhone"
          label="联系电话"
          required="true"
          name="mobilePhone"
          placeholder="报名人联系电话"
          type="tel"
          :rules="[
            { required: true, message: '请填写手机号码' },
            { validator: phoneValidator, message: '请输入正确的手机号格式', trigger: 'onBlur' },
          ]"
        />
        <van-field
          v-model="jionPersonNum"
          label="来人数量"
          required="true"
          name="jionPersonNum"
          placeholder="来人数量"
          type="number"
          :rules="[
            { required: true, message: '请填写参与活动人数，大于1人小于5人' },
            {
              validator: jionPersonNumValidator,
              message: '请填写参与活动人数，大于1人小于5人',
              trigger: 'onBlur',
            },
          ]"
        />
      </van-cell-group>
      <br />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          :loading="loadingStatus"
          loading-type="spinner"
          loading-text="提交中..."
          native-type="submit"
        >
          提交
        </van-button>
      </div>
    </van-form>
  </van-popup>
</template>
